package com.oitsm.plugin.entity;

import org.apache.commons.lang.StringUtils;
/**
 * Cron 计划时间类 
 * @author Arab Runner
 * Jul 30, 2011 7:35:02 PM
 */
public class Cron {
	/**
	 * 相当于 *
	 */
	public final static int ANY = -1;
	/**
	 * 相当于 ?
	 */
	public final static int NONE = -2;
	
	/**
	 * 秒
	 */
	private int s;
	/**
	 * 分
	 */
	private int min;
	/**
	 * 时
	 */
	private int h;
	/**
	 * 天
	 */
	private int day;
	/**
	 * 月
	 */
	private int mon;
	/**
	 * 星期
	 */
	private int dw;
	
	public static Cron parseCron(String cronStr){
		if(StringUtils.isEmpty(cronStr)){
			return null;
		}
		
		String[] items = StringUtils.split(cronStr);
		if(items.length != 6){
			return null;
		}
		
		Cron c = new Cron();
		try{
			c.setS(getVal(items[0],60));
			c.setMin(getVal(items[1],60));
			c.setH(getVal(items[2],24));
			c.setDay(getVal(items[3],31));
			c.setMon(getVal(items[4],12));
			c.setDw(getVal(items[5],7));
		}catch(Exception e){
			return null;
		}
		
		return c;
	}
	
	private static int getVal(String ss,int max){
		if("*".equals(ss)){
			return ANY;
		}else if("?".equals(ss)){
			return NONE;
		}else{
			int si = Integer.parseInt(ss);
			if(si < 0 || si > max){
				throw new RuntimeException("Invalid cron Value!");
			}
			return Integer.parseInt(ss);
		}
	}
	
	public int getS() {
		return s;
	}
	public void setS(int s) {
		this.s = s;
	}
	public int getMin() {
		return min;
	}
	public void setMin(int min) {
		this.min = min;
	}
	public int getH() {
		return h;
	}
	public void setH(int h) {
		this.h = h;
	}
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		this.day = day;
	}
	public int getMon() {
		return mon;
	}
	public void setMon(int mon) {
		this.mon = mon;
	}
	public int getDw() {
		return dw;
	}
	public void setDw(int dw) {
		this.dw = dw;
	}
}
